package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DispatcherServlet {
    public void service(
        HttpRequest request,HttpResponse response) throws IOException {
        String path = request.getUrl();
        File file = new File("./webapps"+path);

//        String fileName = file.getName();
//        String ext = fileName.substring();

        String postfix = path.substring(path.lastIndexOf(".")+1);
        Map<String,String> type = new HashMap<>();
        type.put("html","text/html");
        type.put("css","text/css");
        type.put("js","application/javascript");
        type.put("png","image/png");
        type.put("gif","image/gif");
        type.put("jpg","image/jpeg");
        String value = type.get(postfix);

        if(file.exists() && file.isFile()) {
            //资源存在
            response.setEntily(file);
            /*
            * 1.通过file获取浏览器实际请求的资源的文件名
            * 2.根据文件名截取后缀名
            * 3.根据后缀名设置Content-Type对应的值（http.txt找对应的）
            * */
            //String postfix = file.getCanonicalPath();
            response.addHeader("Content-Type",value);
            response.addHeader("Content-Length",file.length()+"");
        }else {
;            //资源不存在
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File("./webapps/root/404.html");
            response.setEntily(file);
            response.addHeader("Content-Type",value);
            response.addHeader("Content-Length",file.length()+"");
        }
        response.addHeader("Server","WebServer");
    }
}
